package com.why.service.impl;

import cn.hutool.crypto.digest.MD5;
import com.why.enums.UserEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.why.common.utils.PageUtils;
import com.why.common.utils.Query;

import com.why.dao.UsersDao;
import com.why.entity.UsersEntity;
import com.why.service.UsersService;


@Service("usersService")
public class UsersServiceImpl extends ServiceImpl<UsersDao, UsersEntity> implements UsersService {

    @Value("mall.user.token.key")
    private String salt;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UsersEntity> page = this.page(
                new Query<UsersEntity>().getPage(params),
                new QueryWrapper<UsersEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public UsersEntity loginCheck(UsersEntity user) {
        QueryWrapper<UsersEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        UsersEntity entity = baseMapper.selectOne(wrapper);
        if (entity == null) {
            return entity;
        }
        //对用户传进来的数据加入盐
        String slatPassword = MD5.create().setSalt(salt.getBytes()).digestHex(user.getPassword());
        //看看相等不
        return slatPassword.equals(entity.getPassword()) ? entity : null;

    }


    @Override
    public int userRegister(UsersEntity user) {
        QueryWrapper<UsersEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        Integer count = this.baseMapper.selectCount(wrapper);
        if (count >= 1) {
            return UserEnum.USER_NAME_EXIST.getCode();
        }
        return this.baseMapper.insert(user);
    }

}